package com.lsh.payment.service.refund;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.dubbo.rpc.protocol.rest.support.ContentType;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lsh.payment.api.model.basevo.BaseResponse;
import com.lsh.payment.api.model.basevo.CommonResult;
import com.lsh.payment.api.model.basevo.ExceptionStatus;
import com.lsh.payment.api.model.refund.*;
import com.lsh.payment.api.service.refund.IPayRefundRestService;
import com.lsh.payment.core.constant.RedisKeyConstant;
import com.lsh.payment.core.exception.BusinessException;
import com.lsh.payment.core.model.payenum.PayChannel;
import com.lsh.payment.core.model.payenum.RefundStatus;
import com.lsh.payment.core.model.refund.PayRefund;
import com.lsh.payment.core.service.redis.RedisLockService;
import com.lsh.payment.core.service.refund.RefundOrderHandlerService;
import com.lsh.payment.service.BaseService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.text.MessageFormat;

/**
 * Project Name: lsh-payment
 *
 * @author peter
 * @date 17/6/28
 * 北京链商电子商务有限公司
 * Package
 * desc:
 */
@Service(protocol = "rest", validation = "true")
@Path("refund/balance")
@Consumes({MediaType.APPLICATION_JSON})
@Produces({ContentType.APPLICATION_JSON_UTF_8})
public class RefundRestService extends BaseService implements IPayRefundRestService, InitializingBean {

    private final Logger logger = LoggerFactory.getLogger(RefundRestService.class);

    @Autowired
    private RedisLockService redisLockService;

    @Autowired
    private RefundOrderHandlerService refundOrderHandlerService;

    @Override
    public void afterPropertiesSet() throws BusinessException {

    }

    /**
     * 余额无参考退款接口
     * @param refundRequest 下单参数
     * @return
     */
    @Override
    @POST
    @Path("apply")
    public BaseResponse refund(RefundRequest refundRequest) {
        BaseResponse baseResponse = new BaseResponse();

        refundRequest.setVenderId(this.getVenderId());
        String refundKey = MessageFormat.format(RedisKeyConstant.PAY_REFUND_TRADE_LOCK, refundRequest.getRefund_trade_id());
        try {
            logger.info("RefundRequest info is " + JSON.toJSONString(refundRequest));
            //重复下单锁
            if (!redisLockService.lock(refundKey, refundRequest.getRefund_trade_id())) {
                throw new BusinessException(ExceptionStatus.E1002002.getCode(), "退款太频繁,请稍后再试");
            }

            PayRefund payRefund = this.refundOrderHandlerService.createRefundOrder(refundRequest, PayChannel.PURSE_BALANCE_PAY);

            if(payRefund == null){
                throw new BusinessException("2006008", "退款申请记录生成失败");
            }

            if (payRefund.getRefundStatus() == RefundStatus.REFUND_EXCEPTION.getValue()) {
                throw new BusinessException("2006008", "退款申请失败");
            } else if (payRefund.getRefundStatus() == RefundStatus.REFUND_CLOSE.getValue()) {
                throw new BusinessException("2006008", "退款已关闭");
            }

            RefundResponse refundResponse = new RefundResponse();

            refundResponse.setRet(Integer.parseInt(ExceptionStatus.SUCCESS.getCode()));
            refundResponse.setMsg(ExceptionStatus.SUCCESS.getMessage());

            JSONObject content = new JSONObject();
            content.put("payment_refund_no", payRefund.getPaymentRefundNo());

            refundResponse.setContent(content);

            return refundResponse;

        } catch (BusinessException e) {

            baseResponse.setRet(Integer.parseInt(e.getCode()));
            baseResponse.setMsg(e.getMessage());
            logger.error("业务异常:code is {},message is {}.", new String[]{e.getCode(), e.getMessage()});
        } catch (Exception e) {

            baseResponse.setRet(Integer.parseInt(ExceptionStatus.E3001001.getCode()));
            baseResponse.setMsg(ExceptionStatus.E3001001.getMessage());
            logger.error("服务端异常", e);
        } finally {
            try {
                redisLockService.unlock(refundKey);
            } catch (Exception e) {
                logger.error("redis 操作异常", e);
            }
        }

        return baseResponse;
    }


    /**
     * 退款查询接口
     *
     * @param refundQueryRequest 下单参数
     * @return BaseResponse
     */
    @Override
    @POST
    @Path("query")
    public RefundQueryResponse refundQuery(RefundQueryRequest refundQueryRequest) {

        RefundQueryResponse refundQueryResponse = new RefundQueryResponse();
        try {


        } catch (BusinessException e) {

            refundQueryResponse.setRet(Integer.parseInt(e.getCode()));
            refundQueryResponse.setMsg(e.getMessage());
            logger.error("业务异常:code is {},message is {}.", new String[]{e.getCode(), e.getMessage()});
        } catch (Exception e) {

            refundQueryResponse.setRet(Integer.parseInt(ExceptionStatus.E3001001.getCode()));
            refundQueryResponse.setMsg(ExceptionStatus.E3001001.getMessage());
            logger.error("服务端异常", e);
        }

        return refundQueryResponse;
    }
}
